package com.itheima.reggie.controller;

import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.commen.R;
import com.itheima.reggie.domain.User;
import com.itheima.reggie.service.IUserService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.Map;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private IUserService userService;

    //获取验证码
    @PostMapping("/sendMsg")
    public R sendMsg(@RequestBody Map map, HttpSession session) {
        String phone = (String) map.get("phone");


        if (StringUtils.isNotEmpty(phone)) {
            String s = RandomUtil.randomNumbers(6);
            System.out.println(s);
            session.setAttribute(phone, s);
            return R.success("验证码发送成功");
        }


        return R.error("短信发送失败");
    }

    //用户输入验证码，进行登录
    @PostMapping("login")
    public R login(HttpSession session, @RequestBody Map map) {
        String phone = (String) map.get("phone");
        String code = (String) map.get("code");

        Object code1 = session.getAttribute(phone);
        if (code.equals(code1) && code1 != null) {
            LambdaQueryWrapper<User> qw = new LambdaQueryWrapper<>();
            qw.eq(User::getPhone, phone);
            User one = userService.getOne(qw);
            if (one == null) {
                one = new User();
                one.setPhone(phone);
                one.setStatus(1);
                userService.save(one);
            }
            session.setAttribute("user", one.getId());
            return R.success(one);
        }
        return R.error("登录失败");
    }

    @PostMapping("/loginout")
    public R loginout(HttpSession session) {
        session.removeAttribute("user");
        return R.success("退出成功");
    }
}